#include "../../../common/etcd.hpp"
#include <gflags/gflags.h>

#include "message.pb.h"
#include <brpc/server.h>
#include <butil/logging.h>


DEFINE_bool(run_mode, false, "程序的运行模式,false-调试； true-发布；");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:7070", "当前实例的外部访问地址");
DEFINE_int32(listen_port, 7070, "Rpc服务器监听端口");


//1.构造ECho服务
class EchoServiceImpl : public my::EchoService
{
public:
    EchoServiceImpl(){}
    ~EchoServiceImpl(){}
    // 重写虚函数,实现
    virtual void Echo(google::protobuf::RpcController *cntl_base,
                      const my::EchoRequest *request,
                      my::EchoResponse *response,
                      google::protobuf::Closure *done)
    {
        // 1.为了防止忘记管理Closure，使用智能管理对象来管理它
        brpc::ClosureGuard rpc_guard(done);
        // 业务处理
        std::cout << "收到消息" << request->message() << std::endl;
        std::string str = request->message() + "--这是响应";
        response->set_message(str);

        // 如果不使用ClosureGuard
        // done->Run();      //通告业务处理完毕
    }
private:
};

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    initLogger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);
    //1.构造ECho服务
    //2.搭建Rpc服务器
    //3.运行rpc服务
    //4.注册服务
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);
    //-----------------------------------------brpc-------------------------------------------------
    //构造服务器对象
    brpc::Server server;
    //向服务器中，新增EchoService对象
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service,brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1)
    {
        std::cout << "添加rpc服务失败\n";
        return -1; 
    }

    brpc::ServerOptions options;
    options.idle_timeout_sec = -1;  // 没有数据，连接是否关闭，-1表示一直连接
    options.num_threads = 1;        //io线程数量

    //开启服务
    ret = server.Start(FLAGS_listen_port,&options);  
    if(ret == -1)
    {
        std::cout << "启动服务失败\n";
        return -1;
    }
    //---------------------------------------etcd---------------------------------------------------
    //etcd客户端注册服务
    //注册的是 /service/echo/instance ;;  发现的时候 /service/echo
    my::Registry::ptr client = std::make_shared<my::Registry>(FLAGS_etcd_host); //创建etcd客户端
    client->registry(FLAGS_base_service+FLAGS_instance_name,FLAGS_access_host); //etcd客户端注册一个新的服务

    server.RunUntilAskedToQuit();   //阻塞等待服务端运行


    // std::this_thread::sleep_for(std::chrono::seconds(600));
}

